
package com.shiku.imserver.repository;


import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.shiku.imserver.service.IMBeanUtils;
import org.bson.Document;
import org.bson.conversions.Bson;


public class NewFirendRepository
        extends BaseRepository {
    private static final String NEWFIREND = "shiku_newFirend";
    private MongoDatabase newFriendDB;


    @Override
    public boolean initialize() {

        try {

            this.newFriendDB = IMBeanUtils.getBeanManager().getMongoClient().getDatabase("shiku_newFirend");

        } catch (Exception ex) {

            ex.printStackTrace();

            return false;

        }


        return true;

    }


    public void saveNewFirendRecord(String userId, String toUserId, Object from, short type, String content) {

        Document query = new Document("userId", userId);

        query.put("toUserId", toUserId);

        MongoCollection<Document> collection = getCollection(this.newFriendDB, Long.valueOf(userId).longValue());

        Document obj = (Document) collection.find((Bson) query).first();


        Document dbObj = new Document();


        long modifyTime = System.currentTimeMillis() / 1000L;

        if (null == content) {
            content = "";
        }

        dbObj.put("direction", Integer.valueOf(0));

        dbObj.put("type", Short.valueOf(type));

        dbObj.put("content", content);

        dbObj.put("modifyTime", Long.valueOf(modifyTime));

        if (500 == type) {
            dbObj.put("from", from);
        }

        if (null == obj) {

            dbObj.put("userId", userId);

            dbObj.put("toUserId", toUserId);

            dbObj.put("createTime", Long.valueOf(modifyTime));


            collection.insertOne(dbObj);

        } else {

            collection.updateOne((Bson) query, (Bson) new Document("$set", dbObj));

        }


        MongoCollection<Document> collectionTo = getCollection(this.newFriendDB, Long.valueOf(toUserId).longValue());

        query.put("userId", toUserId);

        query.put("toUserId", userId);

        obj = (Document) collectionTo.find((Bson) query).first();

        dbObj.remove("_id");

        dbObj.put("userId", toUserId);

        dbObj.put("toUserId", userId);

        dbObj.put("direction", Integer.valueOf(1));

        if (null == obj) {

            collectionTo.insertOne(dbObj);

        } else {

            collectionTo.updateOne((Bson) query, (Bson) new Document("$set", dbObj));

        }

    }

}


